<template>
	<div
		:class="['app-editor-container', 'app-list-box', `app-list-box-${name}`]"
	>
		<template v-if="multiple">
			<a-checkbox-group
				@change="onChange"
				:value="selectArray"
				:options="items"
				:disabled="disabled || readOnly"
			/>
		</template>
		<template v-else>
			<a-radio-group
				@change="onChange"
				:value="value"
				:options="items"
				:disabled="disabled || readOnly"
			/>
		</template>
	</div>
</template>

<script setup lang="ts">
import { ICodeListItem, IEvent } from '@/core';
import { computed, onBeforeMount, ref, Ref } from 'vue';
import { typeOf, deepCopy } from '@/core/utils';
import { listBoxProps } from './list-box';
import { handleEditorNavParams, useEditorTypeParams, searchEntityData } from '@/hooks/use-editor';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(listBoxProps);
const emit = defineEmits<EditorEmit>();
// 类型校验
const { validateConfig, valueType, valueSeparator } = useEditorTypeParams();
validateConfig();
const { navContext, navViewParam } = handleEditorNavParams(props);
let items: Ref<any[]> = ref([]);
const selectArray: Ref<any> = computed(() => {
	if (props.multiple) {
		if (props.value) {
			if (Object.is('LISTBOX', props.editorType)) {
				let selects: any[] = [];
				if (Array.isArray(props.value)) {
					selects = props.value;
				} else {
					selects = props.value.split(valueSeparator || props.valueSeparator);
				}
				if (props.mode == 'number') {
					for (let i = 0; i < selects.length; i++) {
						selects[i] = parseInt(selects[i]);
					}
				}
				return selects;
			} else {
				if (Array.isArray(props.value)) {
					return props.value;
				} else {
					return props.value.split(valueSeparator || props.valueSeparator);
				}
			}
		}
		return [];
	} else {
		return [props.value];
	}
});

const onChange = ($event: any) => {
	let value: null | string | number | any[] = null;
	if (props.multiple == true) {
		const values = [...$event];
		value = values.join(valueSeparator || props.valueSeparator);
		if (valueType === 'SIMPLES') {
			value = values;
		}
	} else {
		value = $event.target.value;
	}
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	});
};
const formatCodeList = (items: Array<any>) => {
	let matching = false;
	let result: Array<any> = [];
	try {
		items.forEach((item: any) => {
			const type = typeOf(item.value);
			if (type != props.valueType) {
				matching = true;
				if (type === 'number') {
					item.value = item.value.toString();
				} else {
					if (type == 'null') {
						props.valueType == 'number' ? (item.value = 0) : (item.value = '');
					} else if (item.value.indexOf('.') == -1) {
						item.value = parseInt(item.value);
					} else {
						item.value = parseFloat(item.value);
					}
				}
			}
			result.push(item);
		});
		if (matching) {
			console.warn(
				App.ts(
					'common.generic.codelistcast',
					'代码表值类型和属性类型不匹配，自动强制转换'
				)
			);
		}
		return result;
	} catch (error) {
		console.warn(
			App.ts(
				'common.generic.codelistwarn',
				'代码表值类型和属性类型不匹配，自动强制转换异常，请修正代码表值类型和属性类型匹配'
			)
		);
		return [];
	}
};
const loadData = () => {
	let _navContext = deepCopy(navContext);
	let _navViewParam = deepCopy(navViewParam);
	const requestException: string = App.ts(
		'common.generic.requestexception',
		'请求异常'
	);
	if (!props.acParams) {
		console.warn(App.ts('common.generic.miss', '参数不存在'));
		return;
	} else {
		const { serviceName, interfaceName } = props.acParams;
		const { deKeyField, deCodeName } = props;
        searchEntityData(
            serviceName,
            interfaceName,
            _navContext,
            _navViewParam,
            deKeyField,
            deCodeName
        )
        .then((response: any) => {
            if (!response) {
                console.warn(App.ts('common.generic.loadfail', '加载数据失败'));
                return;
            }
            items.value = [...response];
        })
        .catch((error: any) => {
            console.warn(error && error.message ? error.message : requestException);
        });
	}
};
const getCodeList = async () => {
	if (props.codeListTag && props.codeListType) {
		await App.getAppCodeListHelper()
			.getCodeListItems(props.codeListTag, navContext, navViewParam)
			.then((codeListResult: any) => {
				if (codeListResult.ok) {
					const result = formatCodeList(codeListResult.data);
					result.forEach((item: ICodeListItem) => {
						items.value.push({ ...item, label: item.text });
					});
				}
			})
			.catch((error: any) => {
				console.warn(App.ts('common.generic.codenotexist', '代码表不存在'));
			});
	}
};
onBeforeMount(() => {
	if (Object.is('LISTBOX', props.editorType)) {
		getCodeList();
	} else if (Object.is('LISTBOXPICKUP', props.editorType)) {
		loadData();
	}
});
</script>
